package com.elmcode.server.controller;

import com.elmcode.server.constant.FileDirType;
import com.elmcode.server.constant.FilePrefixType;
import com.elmcode.server.utils.AliYunOSSUtil;
import com.elmcode.server.utils.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    AliYunOSSUtil aliYunOSSUtil;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {

        //file----------->oss
        System.out.println(file.getOriginalFilename());
        String originalFilename = file.getOriginalFilename();
        String name = createFileName(originalFilename);

        String path = aliYunOSSUtil.upload(file.getBytes(), name);

        return Result.ok("访问的路径",path);
    }


    private String createFileName(String orginalFilename){
        String objectName = "";
        String prefix = "";
        String postfix = "";
        if(orginalFilename.endsWith(FilePrefixType.IMAGES_JPG.getPrefix())){
            prefix = FileDirType.IMAGES.getDir();
            postfix = FilePrefixType.IMAGES_JPG.getPrefix();
        }
        if(orginalFilename.endsWith(FilePrefixType.IMAGES_PNG.getPrefix())){
            prefix = FileDirType.IMAGES.getDir();
            postfix = FilePrefixType.IMAGES_PNG.getPrefix();
        }
        if(orginalFilename.endsWith(FilePrefixType.IMAGES_WEBP.getPrefix())){
            prefix = FileDirType.IMAGES.getDir();
            postfix = FilePrefixType.IMAGES_WEBP.getPrefix();
        }
        if(orginalFilename.endsWith(FilePrefixType.FILE_SPEECH.getPrefix())){
            prefix = FileDirType.SPEECH.getDir();
            postfix = FilePrefixType.FILE_SPEECH.getPrefix();
        }

        objectName = UUID.randomUUID().toString() + "."+postfix;
        objectName = prefix+"/"+objectName;
        return objectName;
    }

}
